# target
TARGET=nano

BUILD_DIR=build

# wch risc gcc12
CROSS_COMPILE=riscv32-esp-elf-
CC=$(CROSS_COMPILE)gcc
AS=$(CROSS_COMPILE)gcc -x assembler-with-cpp
CP=$(CROSS_COMPILE)objcopy
SZ=$(CROSS_COMPILE)size
LD=$(CROSS_COMPILE)ld
DP=$(CROSS_COMPILE)objdump

# SRC 
SRC_C=src/main.c src/esp32c3_init.c
SRC_S=src/start.S src/vectors.S

SRC_LD=esp32c3.ld

OBJC=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_C:.c=.o)))
OBJS=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_S:.S=.o)))

INC=-Isrc -I. 

CFLAGS = -D ESP32C3 -march=rv32imac_zicsr_zifencei -Wall \
-ffunction-sections -fdata-sections \
 -g3 -O0 -g
 

 
LDFLAGS  = -Wl,--gc-sections -Wl,-Map,"$(BUILD_DIR)/$(TARGET).map" -g -g3 -T$(SRC_LD)  --specs=nano.specs -lnosys -nostartfiles

 
vpath %.c $(sort $(dir $(SRC_C)))
vpath %.S $(sort $(dir $(SRC_S)))

ELF=$(BUILD_DIR)/$(TARGET).elf
BIN=$(BUILD_DIR)/$(TARGET).bin
DIS=$(BUILD_DIR)/$(TARGET).dis 

.PHONY : all clean d c download img

all: $(BUILD_DIR) $(BIN) $(DIS)

$(BUILD_DIR):
	mkdir $@

# cc .c
$(BUILD_DIR)/%.o:%.c 
	@echo .CC $<
	$(CC) $(CFLAGS)  $(INC) -c $<  -o $@
	 

# as .S
$(BUILD_DIR)/%.o:%.S 
	@echo .AS $<
	$(AS) $(CFLAGS) $(INC)  -c $<  -o $@
 

# elf
$(ELF):$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo link elf $@
	$(CC)  $(LDFLAGS) $(OBJC) $(OBJS)  -o $@ 
	@$(SZ) $@ 

#cp .bin
$(BIN):$(ELF)
	@echo elf2image
#	$(CP) -O binary -S $< $@
	../../tools/esptool -c esp32c3 elf2image --flash_mode dio --flash_freq 40m --flash_size 4MB $(BUILD_DIR)/$(TARGET).elf -o $(BUILD_DIR)/$(TARGET).bin


$(DIS):$(ELF)
	@echo objdump dis
	@$(DP) -D -h -s $< > $@

clean:
	rm -rf $(BUILD_DIR)

d:
	make clean
	make all

c:$(BUILD_DIR) $(OBJC) $(OBJS)
	@echo .o

 download:
	../../tools/openocd-esp32/bin/openocd.exe \
	-s ../../tools/openocd-esp32/share/openocd/scripts \
	-f interface/esp_usb_jtag.cfg \
	-f target/esp32c3.cfg \
 	-c "program_esp build/nano.bin 0x00 verify reset" \
 	-c "reset run" \
 	-c exit


#download:
#	esptool -c esp32c3 --baud 115200 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 40m --flash_size detect 0x00 $(BUILD_DIR)/$(TARGET).bin
